/*
 * SessionBean1.java
 *
 * Created on November 8, 2007, 10:12 AM
 * Copyright fsanchez
 */
package gestionbaseem;

import com.computec.baseem.constantes.ConstantesGenerales;
import com.computec.baseem.delegate.BaseEmDelegate;
import com.computec.baseem.exception.BaseEmException;
import com.src.computec.radar.base.ldap.dto.LdapUserDto;
import com.src.computec.radar.base.source.CoreSource;
import com.src.computec.radar.services.utilities.consultas.delegate.ConsultasDelegate;
import com.src.computec.radar.services.utilities.consultas.exception.ConsultasException;
import com.src.computec.radar.services.utilities.dto.ClienteDto;
import com.src.computec.radar.services.utilities.dto.NodoDto;
import com.src.computec.radar.services.utilities.dto.ProveedorDto;
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import com.sun.rave.web.ui.model.Option;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.faces.context.FacesContext;

/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 */
public class SessionBeanBaseEm extends AbstractSessionBean {
    // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
    private int __placeholder;
    private String ldapUser;
    private boolean roleEmpreseaMensajeria=false;
    private String codigoEM="-1";
    private boolean roleComputec=false;    
    private boolean roleAdministrador=false;
    private boolean roleGeneracion=false;
    private Option[] clientesOptions=null;
    private Option[] nodosOptions=null;
    private Option[] proveedorOptions=null;
    private List baseEmList=null;
    private List baseEmDetalle=null;
    private Date minDate=null;
    private Date maxDate=null;
    private Date defaultInitDate=null;
    private boolean renderedAlert=false;
    private boolean renderedTable=false;
    private boolean renderedDropDownEm=false;
    private boolean renderedPanelGridGeneracion=false;
  
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>


    /** 
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionBeanBaseEm() {
	
	//this.setLdapUser("dalmanza.eis");
	this.setLdapUser("fsanchez.computec");
	//System.out.println("SESSION:"+this.getLdapUser());
	//this.setLdapUser(this.getUIdByDomainName(FacesPortletUtil.getPortletRequest(FacesContext.getCurrentInstance()).getRemoteUser()));
	this.setLdapUser(getLdapUser());
	try{
	    this.findRolesUser();	  
	}catch(ConsultasException cex){
	    cex.printStackTrace();
	}
    }

    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected ApplicationBeanBaseEm getApplicationBeanBaseEm() {
        return (ApplicationBeanBaseEm)getBean("ApplicationBeanBaseEm");
    }


    /** 
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
	BaseEmDelegate delegate_=new BaseEmDelegate();
	this.setClientesOptions(this.getClienteOptions());
	ProveedorDto proDto_=new ProveedorDto();
	try{
	    if(this.isRoleEmpreseaMensajeria()){
		this.setNodosOptions(this.getNodosByProveedorOptions(this.getCodigoEM()));
		proDto_.setCodigoProveedor(this.getCodigoEM());
	    }else{

		  this.setNodosOptions(this.getNodosByProveedorOptions(""));

	    }
	}catch(BaseEmException bex){
	    bex.printStackTrace();
	}
	NodoDto nodoDto_=new NodoDto();
	ClienteDto cliDto_=new ClienteDto();
	
	this.setMaxDate(new Date());
	
	
	Calendar cal=Calendar.getInstance();
	
	cal.add(Calendar.MONTH, -6);
	this.setMinDate(cal.getTime());
	
		
	cal.setTimeInMillis(System.currentTimeMillis());
	
	cal.add(Calendar.DAY_OF_MONTH, -7);
	this.setDefaultInitDate(cal.getTime());
	
	try{
	    this.setBaseEmList(delegate_.getListadoBases(proDto_, nodoDto_, cliDto_,this.defaultInitDate,this.maxDate, ""));
	    if(this.getBaseEmList()!=null && this.getBaseEmList().size()>0){
		this.renderedTable=true;
	    }
	  
	}catch(BaseEmException bex){
	    bex.printStackTrace();
	}
	
	
	
	if(this.isRoleAdministrador() || this.isRoleComputec()){
	    this.setProveedorOptions(this.getProveedoresEM());
	}

	   
    }

    /** 
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     * 
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    public void passivate() {
    }

    /** 
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    public void activate() {
    }

    /** 
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    public void destroy() {
    }
    
    private String getUIdByDomainName(String domainName) {
        String[] tokens =  domainName.split(",");
        if (tokens.length > 0) {
            String[] uIdTokens = (tokens[0]).split("=");
            if (uIdTokens.length == 2) {
                return uIdTokens[1];
            }
        }
        return "";
    }

    public String getLdapUser() {
        return ldapUser;
    }

    public void setLdapUser(String ldapUser) {
        this.ldapUser = ldapUser;
    }
    
    public void findRolesUser() throws ConsultasException {
        ConsultasDelegate consultasDelegate = new ConsultasDelegate();
	ConstantesGenerales.getInstance();
        LdapUserDto ldapUserDtoAux = new LdapUserDto();
        ldapUserDtoAux.setIdLdap(this.getLdapUser());	
	
	
        ldapUserDtoAux = consultasDelegate.getLdapUserByPrimaryKey(ldapUserDtoAux);
        
        Iterator iterRoles = ldapUserDtoAux.getRoles().iterator();	
        while(iterRoles.hasNext()) {
            String nombreRole = (String) iterRoles.next();	    
            if (nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_empresa_mensajeria_cn")) == 0) {               		
		this.setRoleEmpreseaMensajeria(true);
		this.setCodigoEM(ldapUserDtoAux.getCodigoEmpresaMensajeria());
	    }else if(nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_administrador_cn")) == 0){
		this.setRoleAdministrador(true);
		this.setRoleGeneracion(true);
		this.setRenderedDropDownEm(true);		
	    } else if(nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_coordinador_auditoria_cn"))==0 
		    || nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_coordinador_logistica_cn"))==0
		    || nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_coordinador_operativo_cn"))==0
		    || nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_coordinador_alistamiento_cn"))==0
		    || nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_coordinador_despachos_cn"))==0
		    || nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_analista_generacion_cn"))==0 
		    || nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_analista_especial_cn"))==0){
		
		this.setRoleGeneracion(true);
		this.setRenderedDropDownEm(true);
	    }else if(this.getLdapUser().endsWith("." + ConstantesGenerales.USUARIO_COMPUTEC) && !this.isRoleAdministrador()){
		this.setRoleComputec(true);		
	    }
        }	
    }
	
    public boolean isRoleEmpreseaMensajeria() {
        return roleEmpreseaMensajeria;
    }

    public void setRoleEmpreseaMensajeria(boolean roleEmpreseaMensajeria) {
        this.roleEmpreseaMensajeria = roleEmpreseaMensajeria;
    }

    public boolean isRoleComputec() {
        return roleComputec;
    }

    public void setRoleComputec(boolean roleComputec) {
        this.roleComputec = roleComputec;
    }

    public boolean isRoleAdministrador() {
        return roleAdministrador;
    }

    public void setRoleAdministrador(boolean roleAdministrador) {
        this.roleAdministrador = roleAdministrador;
    }

    public String getCodigoEM() {
        return codigoEM;
    }

    public void setCodigoEM(String codigoEM) {
        this.codigoEM = codigoEM;
    }
    
    public Option[] getClienteOptions() 
    {
        try
        {
	    
            BaseEmDelegate delegate = new BaseEmDelegate();
         
            List clientesList_ = delegate.getClientes();
	
            Option[] optionsAux = new Option[ clientesList_.size() + 1 ];            
            optionsAux[0] = new Option("","Seleccione...");     
            
            Iterator iter = clientesList_.iterator();
            
            for(int i = 1; iter.hasNext(); i++)
            {
		ClienteDto dto = (ClienteDto)iter.next();
                optionsAux[i] = new Option(dto.getCodigoCliente(),dto.getRazonSocial());
            }   
            
            return optionsAux;           
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    
    public Option[] getNodosByProveedorOptions(String pCodigoProveedor) throws BaseEmException
    {
      
	    Option[] optionsAux=null;
	    if(!pCodigoProveedor.equals("")){
		BaseEmDelegate delegate = new BaseEmDelegate();
		ProveedorDto dto_=new ProveedorDto();
		dto_.setCodigoProveedor(pCodigoProveedor);
		List nodosList_ = delegate.getNodosByProveedor(dto_);

		optionsAux = new Option[ nodosList_.size() + 1 ];            
		optionsAux[0] = new Option("","Seleccione...");     


		Iterator iter = nodosList_.iterator();

		for(int i = 1; iter.hasNext(); i++)
		{
		    NodoDto dto = (NodoDto)iter.next();
		    optionsAux[i] = new Option(dto.getCodigoNodo(),dto.getNombreNodo());
		}   
	    }else{
		optionsAux = new Option[ 1 ];            
		optionsAux[0] = new Option("","Seleccione...");     
	    }
            return optionsAux;                            
    }

    public Option[] getProveedoresEM(){
        try{
	    
            BaseEmDelegate delegate = new BaseEmDelegate();	  
	    
            List proveedoresList_ = delegate.getProveedoresEmpresaMensajeria();
	
            Option[] optionsAux = new Option[ proveedoresList_.size() + 1 ];            
            optionsAux[0] = new Option("","Seleccione...");     
            
            Iterator iter = proveedoresList_.iterator();
            
            for(int i = 1; iter.hasNext(); i++)
            {
		ProveedorDto dto = (ProveedorDto)iter.next();
                optionsAux[i] = new Option(dto.getCodigoProveedor(),dto.getRazonSocial());
            }   
            
            return optionsAux;           
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    public String getFullNamePersonLDAP(String idContact) 
    {        
        try {
            ConsultasDelegate delegate = new ConsultasDelegate();
        
            LdapUserDto dto = new LdapUserDto();
            dto.setIdLdap(idContact);

            dto = delegate.getLdapUserByPrimaryKey(dto);

            if(dto != null)
            {
                return dto.getNombre();
            }
            else
            {
                System.out.println("SessionBeanBaseEm: getFullNamePersonLDAP: No se encontro registro para " + idContact);
                return "";
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }    

   public Locale getLocale() {
       return FacesPortletUtil.getPortletRequest(FacesContext.getCurrentInstance()).getLocale(); 
    }

    /**
     * Getter for property localSetting.
     * @return Value of property localSetting.
     */
    public String getLocaleSetting() {
        String language = this.getLocale().getLanguage();
        return language;
    }
    
    public Option[] getNodosOptions() {
        return nodosOptions;
    }

    public void setNodosOptions(Option[] nodosOptions) {
        this.nodosOptions = nodosOptions;
    }

    public Option[] getClientesOptions() {
        return clientesOptions;
    }

    public void setClientesOptions(Option[] clientesOptions) {
        this.clientesOptions = clientesOptions;
    }

    public List getBaseEmList() {
        return baseEmList;
    }

    public void setBaseEmList(List baseEmList) {
        this.baseEmList = baseEmList;
    }

    public Date getMinDate() {
        return minDate;
    }

    public void setMinDate(Date minDate) {
        this.minDate = minDate;
    }

    public Date getMaxDate() {
        return maxDate;
    }

    public void setMaxDate(Date maxDate) {
        this.maxDate = maxDate;
    }

    public boolean isRenderedAlert() {
        return renderedAlert;
    }

    public void setRenderedAlert(boolean renderedAlert) {
        this.renderedAlert = renderedAlert;
    }

    public boolean isRenderedTable() {
        return renderedTable;
    }

    public void setRenderedTable(boolean renderedTable) {
        this.renderedTable = renderedTable;
    }

    public Date getDefaultInitDate() {
        return defaultInitDate;
    }

    public void setDefaultInitDate(Date defaultInitDate) {
        this.defaultInitDate = defaultInitDate;
    }

    public boolean isRenderedDropDownEm() {
        return renderedDropDownEm;
    }

    public void setRenderedDropDownEm(boolean renderedDropDownEm) {
        this.renderedDropDownEm = renderedDropDownEm;
    }

    public Option[] getProveedorOptions() {
        return proveedorOptions;
    }

    public void setProveedorOptions(Option[] proveedorOptions) {
        this.proveedorOptions = proveedorOptions;
    }

    public List getBaseEmDetalle() {
        return baseEmDetalle;
    }

    public void setBaseEmDetalle(List baseEmDetalle) {
        this.baseEmDetalle = baseEmDetalle;
    }

    public boolean isRenderedPanelGridGeneracion() {
        return renderedPanelGridGeneracion;
    }

    public void setRenderedPanelGridGeneracion(boolean renderedPanelGridGeneracion) {
        this.renderedPanelGridGeneracion = renderedPanelGridGeneracion;
    }

    public boolean isRoleGeneracion() {
        return roleGeneracion;
    }

    public void setRoleGeneracion(boolean roleGeneracion) {
        this.roleGeneracion = roleGeneracion;
    }    
}